package gatperdut.chato.constants;

import gatperdut.chato.model.Chato.Constant.ConstantPackage;
import gatperdut.chato.model.Chato.Constant.Language;

import java.util.ArrayList;
import java.util.List;

import org.eclipse.emf.common.util.EList;
import org.eclipse.emf.common.util.EMap;
import org.eclipse.emf.ecore.EAnnotation;
import org.eclipse.emf.ecore.EEnumLiteral;

public final class CSConstantsLanguages {

    public static Language getLanguageFromString( String which ) {
        EList<EEnumLiteral> literals = ConstantPackage.Literals.LANGUAGE.getELiterals();

        for ( EEnumLiteral literal : literals ) {
            EAnnotation annotation = literal.getEAnnotation( "aliases" );
            EMap<String, String> details = annotation.getDetails();
            for ( String value : details.values() ) {
                if ( which.equalsIgnoreCase( value ) ) {
                    return (Language) literal.getInstance();
                }
            }
        }

        return null;
    }

    public static List<String> getLanguageAliases( Language l ) {

        EEnumLiteral literal = ConstantPackage.Literals.LANGUAGE.getEEnumLiteral( l.getValue() );
        if ( literal == null ) {
            return null;
        }

        List<String> aliases = new ArrayList<String>();
        EAnnotation annotation = literal.getEAnnotation( "aliases" );
        for ( String alias : annotation.getDetails().values() ) {
            aliases.add( alias );
        }

        return aliases;
    }

    public static String getLanguageAliasesString( Language l ) {
        EEnumLiteral literal = ConstantPackage.Literals.LANGUAGE.getEEnumLiteral( l.getValue() );
        if ( literal == null ) {
            return null;
        }
        boolean firstAliasAdded = false;
        List<String> aliases = CSConstantsLanguages.getLanguageAliases( l );
        StringBuilder sb = new StringBuilder( "" );
        for ( String alias : aliases ) {
            if ( !firstAliasAdded ) {
                firstAliasAdded = true;
                sb.append( alias );
            }
            else {
                sb.append( "/" + alias );
            }
        }
        return sb.toString();
    }
}
